//
//  Util.m
//  Example
//
//  Created by Andney Jack on 2020/6/3.
//  Copyright © 2020 annidy. All rights reserved.
//

#import "Util.h"

@implementation Util

+ (UIInterfaceOrientationMask)ct_supportedInterfaceOrientationsForVC:(UIViewController *)vc
{
    if (vc.presentedViewController) {
        if ([self ct_shouldRotateDependOnChildViewController:vc]) {
            return [vc.presentedViewController supportedInterfaceOrientations];
        }
    } else {
        if ([vc isKindOfClass:[UINavigationController class]]) {
            UINavigationController *nav = (UINavigationController *)vc;
            if (nav.viewControllers.count > 0) {
                return [nav.topViewController supportedInterfaceOrientations];
            }
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            UITabBarController *tabController = (UITabBarController *)vc;

            if (tabController.selectedIndex >= 0 && tabController.selectedIndex < tabController.viewControllers.count) {
                return [tabController.selectedViewController supportedInterfaceOrientations];
            }
        }
    }

    return UIInterfaceOrientationMaskPortrait;
}

+ (BOOL)ct_shouldAutorotateForVC:(UIViewController *)vc
{
    if (vc.presentedViewController) {
        if ([self ct_shouldRotateDependOnChildViewController:vc]) {
            return [vc.presentedViewController shouldAutorotate];
        }
    } else {
        if ([vc isKindOfClass:[UINavigationController class]]) {
            UINavigationController *nav = (UINavigationController *)vc;
            if (nav.viewControllers.count > 0) {
                return [nav.topViewController shouldAutorotate];
            }
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            UITabBarController *tabController = (UITabBarController *)vc;

            if (tabController.selectedIndex >= 0 && tabController.selectedIndex < tabController.viewControllers.count) {
                return [tabController.selectedViewController shouldAutorotate];
            }
        }
    }

    return NO;
}

+ (BOOL)ct_shouldRotateDependOnChildViewController:(UIViewController *)vc
{
    if (vc.presentedViewController.isViewLoaded &&
        vc.presentedViewController.view.window &&
        !vc.presentedViewController.isBeingDismissed) {
        return YES;
    }

    return NO;
}

@end
